﻿
# coding:utf-8

import math
from lib import pymunk      # Import pymunk..

GROUP_PLAYER_BULLET  = 1
GROUP_ENEMY_BULLET   = 2
GROUP_PLAYER         = 10
GROUP_ENEMY          = 11
GROUP_WALL           = 100

space = pymunk.Space()      # Create a Space which contain the simulation
space.gravity = 0,0     # Set its gravity

update_list = {}

def Reg(body, view):
    update_list[body] = view

def Remove(body):
    if body in update_list:
        space.remove(body, *body.shapes)
        del update_list[body]

def Update(dt):
    _dt = dt / 7
    for i in range(7):
        space.step(_dt)

    for body,view in update_list.items():
        view.SetPos(int(body.position.x), int(body.position.y))
        view.SetAngle(math.degrees(body.angle))

def Start():
    def remove(first_shape, second_shape):
        a, b = first_shape.group, second_shape.group
        if a > b:
            first_shape, second_shape = second_shape, first_shape
            a, b = first_shape.group, second_shape.group

        body = first_shape.body
        body2= second_shape.body

        # 子弹的话就移除
        if a == GROUP_PLAYER_BULLET:
            update_list[body]._del()
            space.remove(first_shape, body)
            if b == GROUP_ENEMY:
                update_list[body2].attr['hp'] -= update_list[body].dmg
            del update_list[body]
        elif a == GROUP_ENEMY_BULLET:
            if b == GROUP_WALL:
                update_list[body]._del()
                space.remove(first_shape, body)
                del update_list[body]
            elif b == GROUP_PLAYER:
                update_list[body2].attr['hp'] -= update_list[body].dmg

    def collision_handler(space, arb):
        first_shape = arb.shapes[0]
        second_shape = arb.shapes[1]
        space.add_post_step_callback(remove, first_shape, second_shape)

    #space.add_collision_handler(GROUP_PLAYER_BULLET, GROUP_ENEMY, collision_handler)
    space.add_collision_handler(0, 0, collision_handler)
